<template>
	<view>
		<view class="card tn-padding-sm tn-margin-sm">
			<tn-form :model="form" ref="form" :labelWidth="180" :errorType="['message', 'toast']">
				<tn-form-item label="时间：" prop="createTime1">
				  <uni-datetime-picker  :clearIcon="false" :border="false" placeholder="请选择时间"
									   v-model="form.createTime1" />
				</tn-form-item>
				<tn-form-item label="救援费用：" prop="jyMoney">
					<tn-input type="number" v-model="form.jyMoney" />
					元
				</tn-form-item>
				<tn-form-item label="发票照片：" prop="invoicePhoto">
					<tn-image-upload :beforeUpload="beforeUpload"  @on-success="onSuccess" ref="imageUpload" :maxCount="1" :header="header" :action="action"></tn-image-upload>
				</tn-form-item>
				<tn-form-item label="备注：" prop="remark">
					<tn-input type="textarea" v-model="form.remark" />
				</tn-form-item>

				<view class="tn-flex tn-flex-row-center tn-padding-xl">
				  <tn-button @click="submit" backgroundColor="tn-bg-blue" style="width: 80%" fontColor="tn-color-white">保存
				  </tn-button>
				</view>
			</tn-form>
		</view>
		<tn-modal v-model="erweima" :custom="true">
			<view class="custom-modal-content tn-flex tn-flex-direction-column tn-flex-col-center">
				<p style="margin-bottom: 8px;">发票照片</p>
				<canvas id="qrcode" canvas-id="qrcode" style="width: 200px; height: 200px"></canvas>
				<tn-button @click="downloadPDFFn" backgroundColor="tn-bg-blue" style="width: 80%; margin-top: 16px" fontColor="tn-color-white">下载图片</tn-button>
			</view>
		</tn-modal>
	</view>
</template>

<script>
import {saveNextStep} from "@/pages/rescue/add/funtion";

let timer = null;
import config from '@/config';
import UQRCode from '@/node_modules/uqrcodejs/uqrcode.js';
import { getToken } from '@/utils/auth';
import { getJyInvoicePhoto, addJyInvoicePhoto } from '@/api/jyInvoicePhoto';
import dayjs from 'dayjs';
import { blobToBase64, base64ToFile } from'@/utils/typeConversion.js'
import {toast} from "@/utils/common";
export default {
	data() {
		return {
			erweima: false,
			dragAddress: '',
			url: '',
			action: config.baseUrl + '/exam/common/api/file/upload',
			header: {
				token: getToken()
			},
			form: {
				createTime1:'',
				jyBaseId: null,
				jyMoney: '',
				invoicePhoto: '',
				remark: ''
			},
			rules: {
				// jyMoney: [
				// 	{
				// 		required: true,
				// 		message: '请输入救援费用',
				// 		trigger: ['change']
				// 	}
				// ],
				// invoicePhoto: [
				// 	{
				// 		required: true,
				// 		message: '请上传发票照片',
				// 		trigger: ['change']
				// 	}
				// ]
			}
		};
	},
	// 必须要在onReady生命周期，因为onLoad生命周期组件可能尚未创建完毕
	onReady() {
		this.$refs.form.setRules(this.rules);
    uni.getStorage({
      key: 'TIANBAOID',
      success: (res) => {
        console.log(res.data);
        if (res.data) {
          this.getList(res.data);
          this.form.jyBaseId = res.data;
        }
      }
    });
	},
	onNavigationBarButtonTap(e) {
    // 08.12 解决卷宗修改车牌，数据不同步问题
    this.submit('pdf')
	},
	methods: {
    beforeUpload(index,list){
      timer = setTimeout(()=>{
        uni.showLoading({
          title: '上传中'
        });
      },500)
    },
    onSuccess(e){
      clearTimeout(timer);
      toast('图片上传成功')
    },
		downloadPDFFn() {
			this.erweima = false;
			window.location.href = this.dragAddress
		},
		creatImg() {
			// 获取uQRCode实例
			var qr = new UQRCode();
			// 设置二维码内容
			qr.data = this.dragAddress;
			// 设置二维码大小，必须与canvas设置的宽高一致
			qr.size = 200;
			// 调用制作二维码方法
			qr.make();
			// 获取canvas上下文
			var canvasContext = uni.createCanvasContext('qrcode', this); // 如果是组件，this必须传入
			// 设置uQRCode实例的canvas上下文
			qr.canvasContext = canvasContext;
			// 调用绘制方法将二维码图案绘制到canvas上
			qr.drawCanvas();
		},
		getList(id) {
			getJyInvoicePhoto(id).then((res) => {
				if (res.data) {
					this.form = res.data;
					let imgArr = res.data.invoicePhoto.split(',');
					let objImgArr = [];
					if (res.data.invoicePhoto) {
						objImgArr = imgArr.map((item) => {
							return {
								url: item,
								progress: 100,
								response: {
									data: {
										url: item
									}
								}
							};
						});
					}
					this.$refs.imageUpload.lists = objImgArr;
					this.dragAddress = imgArr[0];
				}else{
          this.form.createTime1 =  dayjs().format('YYYY-MM-DD HH:mm:ss')
        }
			});
		},
		imgChange() {
			let arr = [];
			this.$refs.imageUpload.lists.forEach((val) => {
				if (val.progress == 100) {
					arr.push(val.response.data.url);
				}
			});
			this.form.invoicePhoto = arr.join();
		},
		submit(type) {
			this.$refs.form.validate((valid) => {
				if (valid) {
					this.imgChange();
					addJyInvoicePhoto(this.form).then((res) => {
            this.dragAddress = this.form.invoicePhoto;
            this.getList(this.form.jyBaseId)
            setTimeout(()=>{
              saveNextStep(type, res, this)
            },500)
          });
					console.log('验证通过');
				} else {
					console.log('验证失败');
				}
			});
		},
		zhuanBase64(){
			blobToBase64(this.$refs.imageUpload.lists[0].file).then(res=>{

				// console.log('res',res);
				this.base64Url = res;

				// 手动上传
				// this.$refs.imageUpload.upload()
			})
		}
	}
};
</script>

<style lang="scss" scoped>
.card {
	background-color: #fff;
	box-shadow: 0px 4px 20px 0px rgba(0, 3, 72, 0.1);
	border-radius: 8px;
}
::v-deep{
		.tn-form-item--left__content__label{
			font-weight: 700;
		}
	}
</style>
